<?php
class Flattr extends DbConnector {
	private $episodes;
	private $counter;
	private $olderMonth;

	function __construct($counter) {
		($counter == "") ? $counter = $this->calcLastMonth() : $counter = mysql_real_escape_string($counter);
		$query = "SELECT podcast_tag, filename, created, name FROM `pp_loaded_episodes`
					LEFT JOIN `pp_podcasts` ON tag = podcast_tag
					WHERE YEAR(`created`) = YEAR('$counter') AND MONTH(`created`) = MONTH('$counter');";

		$this->episodes = $this->fetchAll(self::$db->query($query));
		$this->counter = $this->calcCounter($counter);
		$this->olderMonth = date("Ym", strtotime($counter)) < date("Ym", time());
	}

	public function getContent() {
		$player = new AudioPlayer();
		$content = "";

		// append all episodes with flattr integration
		$flattrableEpisodes = $this->selectFlattrableEpisodes();

		if(!count($flattrableEpisodes)) {
			$content .= "<b>No episodes downloaded in ";
			$content .= "<a href=\"".ROOT."flattr/".$this->counter["prev"]."\" title=\"Go to previous month\">&laquo; </a>";
			$content .= date("F Y", $this->counter["now"]);
			$content .= "<a href=\"".ROOT."flattr/".$this->counter["next"]."\" title=\"Go to next month\"> &raquo;</a>";
			$content .= "</b>";
		} else {
			$content .= "<b>You downloaded ".count($flattrableEpisodes)." episodes in ";
			$content .= "<a href=\"".ROOT."flattr/".$this->counter["prev"]."\" title=\"Go to previous month\">&laquo; </a>";
			$content .= date("F Y", $this->counter["now"]);
			$content .= "<a href=\"".ROOT."flattr/".$this->counter["next"]."\" title=\"Go to next month\"> &raquo;</a></b><br>\n<br>\n";

			foreach ($flattrableEpisodes as $episode) {
				// link to post? (that is not the audiofile it self)
				(substr($episode["link"], strlen($episode["link"])-3, 3) == "mp3") ? $episode["link"] = "" : $episode["link"];
				(substr($episode["link"], strlen($episode["link"])-3, 3) == "m4a") ? $episode["link"] = "" : $episode["link"];

				($episode["link"] != "") ? $episode["title"] = ' <a href="'.$episode["link"].'" target="_blank">'.$episode["title"].'</a>' : $episode["link"];

				$content .= '<article class="item">
							<div>
								<img src="'.ROOT.'logo/'.$episode["tag"].'" class="pclogo" alt="Podcastcover" />
								<div class="right">
									<p class="published"><span class="today">'.$episode["created"].'</span></p>
									<br />
									<div class="flattr">'.$episode["flattr"].'</div>
								</div>
								<div>
									<h3 class="title">'.$episode["title"].'</h3>
									<p class="feed">'.$episode["filename"].'<br>
									by <a href="'.ROOT.'episodes/'.$episode["tag"].'">'.$episode["name"].'</a></p>
								</div>
							</div>
							<br />
							'.$player->getPlayer($episode["tag"],$episode["filename"]).'
							</article><br />';
			}
		}

		//$content .= '<script src="https://api.flattr.com/js/0.6/load.js?mode=auto&amp;popout=0&amp;button=compact" type="text/javascript"> </script>';

		return $content;
	}

	private function fetchAll($result) {
		// order by podcast tag
		$ordered = array();

		while ($row = @mysql_fetch_assoc($result)) {
			if (!isset($ordered[$row["podcast_tag"]])) {
				$ordered[$row["podcast_tag"]] = array();
			}

			$ordered[$row["podcast_tag"]][] = $row;
		}

		return $ordered;
	}

	private function selectFlattrableEpisodes() {
		$flattrableEpisodes = array();
		$checkerArray = array();

		// iterate through all downloaded episodes, download the feed once for each
		// podcast and see if the episode have a flattr rel
		foreach ($this->episodes as $orderedEpisodes) {
			$podcastTag = $orderedEpisodes[0]["podcast_tag"];

			$feed = new Feed($podcastTag);
			$feedContent = $feed->getCachedContent();

			// get all items
			preg_match_all("#(<item>.*</item>)#Us", $feedContent, $matches);

			foreach ($matches[1] as $item) {
				// find the payment rel
				preg_match('#.*link rel="payment".*href="(.*)"#', $item, $match);
				$flattrUrl = @$match[1];

				// find the episode title, link and filename
				preg_match('#.*<title>(.*)[\r\n]?</title>#', $item, $match);
				$title = @$match[1];

				preg_match('#.*<link>(.*)[\r\n]?</link>#', $item, $match);
				$link = @$match[1];

				preg_match('#<enclosure.*url=".*/(.*\.[ampAMP34]{3})#', $item, $match);
				$filename = @$match[1];

				// if the episode (filename) is from the selected month, push into result array
				foreach ($orderedEpisodes as $episode) {
					if($episode["filename"] == $filename && !in_array($filename, $checkerArray)) {
						array_push($checkerArray, $filename);

						($episode["name"] == "") ? $episode["name"] = "<i>deleted</i>" : $episode;

						$flattrDiv = $this->generateFlattrDiv($flattrUrl);
						$flattrableEpisodes[] = array("name" => $episode["name"],
						                              "title" => $title,
						                              "flattr" => $flattrDiv,
						                              "filename" => $filename,
                                                      "tag" => $podcastTag,
                                                      "link" => $link,
						                              "created" => $episode["created"]);
						break;
					}
				}
			}
		}

		// sort the result by created date
		function sortByDate($a,$b) {
			$timeA = strtotime($a["created"]);
			$timeB = strtotime($b["created"]);

			if ($timeA == $timeB) {
				return 0;
			}
			return ($timeA > $timeB) ? -1 : 1;
		}
		usort($flattrableEpisodes, "sortByDate");

		return $flattrableEpisodes;
	}

	private function generateFlattrDiv($flattrUrl) {
		$div = "";

		// only show the flattr div for past month
		if($this->olderMonth){
			if($flattrUrl == "") {
				$div = "(no Flattr)";
			} else {
				// select all the data from url
				preg_match("#user_id=(.*)[&\"]#U", $flattrUrl, $match);
				$userid = @urldecode($match[1]);

				preg_match("#url=(.*)[&\"]#U", $flattrUrl, $match);
				$url = @urldecode($match[1]);

				preg_match("#category=(.*)[&\"]#U", $flattrUrl, $match);
				$category = htmlentities(@urldecode($match[1]));

				preg_match("#title=(.*)[&\"]#U", $flattrUrl, $match);
				$title = htmlentities(@urldecode($match[1]));

				preg_match("#description=(.*)[&\"]#U", $flattrUrl, $match);
				$description = htmlentities(@urldecode($match[1]));

				preg_match("#tags=(.*)[&\"]#U", $flattrUrl, $match);
				$tags = @urldecode($match[1]);

				$div = '<div><a class="FlattrButton" rel="payment" ';
				$div .= "href=\"$flattrUrl\" ";
				$div .= "data-flattr-uid=\"$userid\" ";
				$div .= "data-flattr-url=\"$url\" ";
				$div .= "data-flattr-language=\"en_GB\" ";
				$div .= "data-flattr-category=\"$category\" ";
				$div .= "data-flattr-title=\"$title\" ";
				$div .= "data-flattr-description=\"$description\" ";
				$div .= "data-flattr-tags=\"$tags\" >";
				$div .= '<img src="'.ROOT.'app/images/flattr.png" style="border: 0;" alt="Flattrbutton">';
				$div .= "</a></div>";
			}
		}

		return $div;
	}

	private function calcCounter($counter) {
		$minusCounter = date("Y-m-01", strtotime($counter." - 1 Month"));
		$plusCounter = date("Y-m-01", strtotime($counter." + 1 Month"));
		$counter = strtotime($counter);

		return array("prev" => $minusCounter,
					 "now" => $counter,
					 "next" => $plusCounter);
	}

	private function calcLastMonth() {
		// strotime("-1 month") produces wrong results at the end of some month
		$month = date("m", time()) - 1;
		$year = date("Y", time());

		if ($month == 0) {
			$month = 12;
			$year = $year-1;
		}

		return "$year-$month-01";
	}
}

?>
